/*
 * @Author: zhangxiao
 * @Email: zhangxiao0125@163.com
 * @Date: 2020-06-18 11:52:48
 * @Last Modified by: zhangxiao
 * @Last Modified time: 2020-07-15 11:19:27
 * @Description: 课程发布-视频
 */

import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_code_framework/utils/global.dart';
import 'package:flutter_sfsymbols/flutter_sfsymbols.dart';
import 'package:image_picker/image_picker.dart';
import 'package:progress_dialog/progress_dialog.dart';
import 'package:video_compress/video_compress.dart';
import 'package:video_player/video_player.dart';
import 'lesson_publish_event.dart';


// ignore: must_be_immutable
class PublicVideoLesson extends StatefulWidget {
  String videoPath;
  PublicVideoLesson({Key key,this.videoPath}) : super(key: key);
  @override
  _PublicVideoLessonState createState() => _PublicVideoLessonState();
}

class _PublicVideoLessonState extends State<PublicVideoLesson> {
  VideoPlayerController videoController;
  final _picker = ImagePicker();

  ProgressDialog pr;
  VideoPlayer videoPlayer;
  bool _isPlay=false;
  String _videoPath='';
  bool _isShowButtom=false;
  bool flag=false;
  int _inSeconds=0;
  int _secods=0;
  VoidCallback videoPlayerListener;
  double slider=0;
 // String videoPath;
  @override
  void initState() {
    super.initState();
    if(widget.videoPath!=null){
      _videoPath=widget.videoPath;
     _videoPlay(_videoPath);
    }
  }
 
  @override
  void dispose() {
    super.dispose();
    videoController.dispose();
    videoController=null;
  }
 
  @override
  Widget build(BuildContext context) {
    G.eventBus.fire(LessonPublishEvent(videoPath:_videoPath)); //发送订阅消息给父页面
    if(videoController!=null){
       return Container(
         color:Colors.black,
         width: MediaQuery.of(context).size.width,
         child:Column(
            children: <Widget>[        
              Expanded(
                child: Stack(
                  children: <Widget>[
                      Container(
                        width: MediaQuery.of(context).size.width,
                        child: videoController.value.initialized
                            ? AspectRatio(
                                aspectRatio: videoController.value.aspectRatio,
                                child: Container(
                                  color: Colors.black,
                                  child: VideoPlayer(videoController),
                                ),
                              )
                            : Center(                     
                                child: Text(
                                  'Loading.....',
                                  style: TextStyle(color: Colors.white),
                                ),
                              )
                        ),
         
                 
                      Visibility( 
                        visible:_isShowButtom,
                        child: Positioned(
                        left:24,
                        bottom: 22,
                        child:IconButton(icon:Icon(SFSymbols.trash_circle_fill,size: 46.0),color:Colors.white,onPressed: (){
                          if(_videoPath.indexOf('http')>-1){
                            widget.videoPath="";
                          }else{
                            Directory(_videoPath).delete(recursive: true).then((FileSystemEntity fileSystemEntity) {});
                          }
                          _videoPath='';
                          videoController=null;
                          setState(() {
                            
                          });
                          })
                        )),

                      Visibility( 
                          visible: _isShowButtom,
                          child:Positioned(
                          right:24,
                          bottom: 16,
                          child:GestureDetector(
                                  child: Container(
                                      height: 50,
                                      width: 50,
                                      decoration: new BoxDecoration(
                                      color: Color.fromRGBO(57,135,110,1),
                                      borderRadius: BorderRadius.all(Radius.circular(150.0)),
                                      ),
                                      child:Icon(_isPlay?Icons.pause:Icons.play_arrow,color: Colors.black,size: 35.0,)),
                                    onTap:_isPlayOrPause,
                            )
                )),
              ],
          ))
       ]));
    }
   else{
    return Container(
      color:Color.fromRGBO(232,232,232,0.6),
      child:Column(
         children: <Widget>[
         Expanded(
           child:Center(child: Text('请单击录制按钮进行录制',style: TextStyle(color:Theme.of(context).primaryTextTheme.caption.color,fontSize: 24.0,decoration: TextDecoration.none))),
           flex: 3,
         ),
        GestureDetector(
          child:Container(
              height: 50.0,
              width: 50.0,
              margin: EdgeInsets.only(bottom:16.0),
               decoration: new BoxDecoration(
                color: Color.fromRGBO(236,115,100,1),
                borderRadius: BorderRadius.all(Radius.circular(150.0)),
              ),
              child:Icon(Icons.stop,color: Colors.white,size: 30.0,)),
          onTap: () async {
               PickedFile video=await _picker.getVideo(source:ImageSource.camera);
               pr = ProgressDialog(
                    context,
                    type: ProgressDialogType.Normal,
                    isDismissible: true,
                  );
                  pr.style(
                    message: '视频压缩中...',
                    borderRadius: 10.0,
                    backgroundColor: Colors.white,
                    progressWidget: CircularProgressIndicator(),
                      elevation: 10.0,
                    insetAnimCurve: Curves.easeInOut,
                    progress: 0.0,
                    maxProgress: 100,
                    progressTextStyle: TextStyle(
                        color: Colors.black, fontSize: 13.0, fontWeight: FontWeight.w400),
                    messageTextStyle: TextStyle(
                        color: Colors.black, fontSize: 19.0, fontWeight: FontWeight.w600),
                  );
                  pr.show();
                  await runFlutterVideoCompressMethods(File(video.path)).then((cv)=>{
                    pr.hide(),
                   _videoPath=cv.path,
                  });
                  _isPlay=false;
                 _videoPlay(_videoPath);
           },
        )
       ]));
    }
  }

  //播放控件初始化
  _videoPlay(v) async {
      if(v.toString().indexOf('http')>-1){
       videoController =VideoPlayerController.network(v);
      }else{
        videoController =VideoPlayerController.file(File(v));
        _videoPath=v;
      }
      await videoController.initialize().then((value) => {
       _inSeconds=videoController.value.duration.inSeconds.toInt(),
       _isShowButtom=true,
      });
     
        setState(() { });
    }
 
   //判断按钮状态
   _isPlayOrPause() async{
     if(!flag){
        _secods=0;
     }

     if(!_isPlay){
       await videoController.play();
        if(_secods>0){
          videoController.seekTo(Duration(seconds: _secods));
       }
        videoPlayerListener = () {
          videoController.position.then((pos) {
           setState(() {
            _secods = pos.inSeconds.toInt();
          });
          });
          if (_inSeconds==_secods)  {
            videoController.removeListener(videoPlayerListener);
            _isPlay=false;
            videoController.seekTo(Duration(seconds:1));
            videoController.pause();
            if(mounted) setState(() {});
          }
       };
       videoController.addListener(videoPlayerListener);
       _isPlay=true;
     }else{
       await videoController.pause();
         videoController.removeListener(videoPlayerListener);
      _isPlay=false;
     }
     setState(() {
     });
   }

   runFlutterVideoCompressMethods(File videoFile) async {
     return await VideoCompress.compressVideo(
      videoFile.path,
      quality: VideoQuality.HighestQuality,
      deleteOrigin: true
    );
  }
}
  
  
  


  